/* eslint-disable */
import Vue from 'vue';
import Router from 'vue-router';
import Login from '@/base/Login.vue';
import Base from '@/base/Base.vue';
import { createAxiosObj } from '@/axios/request';
import { state, action } from '@/store/store';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/base',
      name: 'Base',
      component: Base
    }
  ],
});

// 全局定义组件唤起/关闭通信方法
window._comCall = function (query) {
  // 唤起
  if (typeof query === 'object' && query !== null) {
    if (query.moduleName) {
      router.push({
        name: 'Webview',
        query: {
          moduleName: query.moduleName, // 模块名称
          tit: query.tit || '' // 模块标题
        }
      })
    } else {
      console.warn('未定义组件名')
    }
  }
  // 关闭
  if (query === 'close') {
    router.go(-1)
  }
}

router.beforeEach((to, from, next) => {
  const token = state.classInfo.token
  if (token && to.name === 'Login') {
    return next({ name: 'Base' });
  }
  // 没classInfo默认未登录
  if (!token && to.name !== 'Login') {
    return next({ name: 'Login' });
  }
  // 用户已登录但没有实例化rq
  if (!Vue.prototype.$rq && token) {
    createAxiosObj(state.classInfo);
  }
  // 路由级设置title
  action.setTitAction(to.query.tit ? to.query.tit : '');
  next();
});

export default router;
